package root.electronclass.electronclass.grade.curriculum

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import root.electronclass.electronclass.R
import root.electronclass.electronclass.adapter.GridSpacingItemDecoration
import root.electronclass.electronclass.common.base.BasicAdapter
import root.electronclass.electronclass.common.base.ViewBindingFragment
import root.electronclass.electronclass.common.util.ToastUtil
import root.electronclass.electronclass.databinding.FragmentClassCurriculumBinding
import root.electronclass.electronclass.databinding.FragmentClassCurriculumHeaderBinding
import root.electronclass.electronclass.databinding.FragmentClassCurriculumItemBinding
import root.electronclass.electronclass.databinding.FragmentClassCurriculumTitleBinding
import root.electronclass.electronclass.ext.chineseNumber
import root.electronclass.electronclass.ext.doOnSearch
import root.electronclass.electronclass.ext.dp
import root.electronclass.electronclass.ext.onResult
import root.electronclass.electronclass.ext.showAvatar
import root.electronclass.electronclass.ext.toDateYyyyMMdd
import root.electronclass.electronclass.grade.model.ClassCurriculumItem
import root.electronclass.electronclass.grade.viewmodel.ClassCurriculumViewModel
import root.electronclass.electronclass.grade.viewmodel.WeekType
import root.electronclass.electronclass.other.AttestationActivity
import java.util.Calendar

/**
 * 课程表
 * @author Lokiy
 * @date 2023/2/11 13:21
 */
class ClassCurriculumFragment : ViewBindingFragment<FragmentClassCurriculumBinding>() {

    private val viewModel: ClassCurriculumViewModel by viewModels()
    private var currentDayOfWeek: Int = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)
    private var lastSuccessTime = 0L
    private var currentWeekType = WeekType.CURRENT

    private val headerAdapter = BasicAdapter<ClassCurriculumItem, FragmentClassCurriculumHeaderBinding> { holder, item ->
        holder.binding.itemName.text = item.subject.replace("今天", "")
        holder.binding.itemTime.text = item.startTime
        holder.binding.itemToday.isVisible = item.subject.contains("今天")
        holder.binding.root.isSelected = item.subject.contains("今天")
    }
    private val titleAdapter = BasicAdapter<String, FragmentClassCurriculumTitleBinding> { holder, item ->
        holder.binding.itemName.text = getString(R.string.class_curriculum_prefix, (holder.position + 1).toString())
        holder.binding.itemTime.text = item
    }
    private val adapter = BasicAdapter<ClassCurriculumItem, FragmentClassCurriculumItemBinding> { holder, item ->
        val column = holder.adapterPosition % 7
        val row = holder.adapterPosition / 7 + 1
//        holder.binding.itemPosition.isVisible = false
//        holder.binding.itemPosition.text = getString(R.string.class_curriculum_prefix, row.chineseNumber)
        holder.binding.itemName.text = item.subject
//        holder.binding.itemTime.text = item.showTime
        (holder.binding.itemTeacherAvatar.parent as View).isGone = item.teacherName.isNullOrEmpty()
        holder.binding.itemTeacherName.text = item.teacherName
        holder.binding.itemTeacherAvatar.showAvatar(item.photo, if (item.gender == 2) 0 else 1)
        //0 -> 2
        //1 -> 3
        //2 -> 4
        //3 -> 5
        //4 -> 6
        //5 -> 7
        //6 -> 1
        val dayOfWeek = (column + 2).takeIf { it <= 7 } ?: 1
        holder.binding.itemBg.isActivated =
            currentWeekType == WeekType.CURRENT && currentDayOfWeek == dayOfWeek && binding.search.text.toString() != item.subject
        val isSearchItem = item.subject.isNotEmpty() && binding.search.text.toString() == item.subject
        holder.binding.itemBg.isSelected = isSearchItem
        holder.binding.ivSearch.isVisible = isSearchItem
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        //
        fun updateWeekType(pointTo: Int) {
            val type = when (currentWeekType) {
                WeekType.CURRENT -> if (pointTo > 0) WeekType.NEXT else WeekType.LAST
                WeekType.NEXT -> if (pointTo > 0) WeekType.LAST else WeekType.CURRENT
                WeekType.LAST -> if (pointTo > 0) WeekType.CURRENT else WeekType.NEXT
            }
            currentWeekType = type
            binding.tvWeek.text = when (type) {
                WeekType.CURRENT -> getString(R.string.class_current_week)
                WeekType.NEXT -> getString(R.string.class_next_week)
                WeekType.LAST -> getString(R.string.class_last_week)
            }
            viewModel.loadData(currentWeekType)
        }

        binding.ivLeft.setOnClickListener {
            updateWeekType(-1)
        }

        binding.ivRight.setOnClickListener {
            updateWeekType(1)
        }
        binding.search.doOnSearch {
//            viewModel.load(text = it)
            adapter.notifyDataSetChanged()
            false
        }

        binding.headerRecycler.adapter = headerAdapter

        binding.recycler.adapter = adapter
        binding.classSign.setOnClickListener {
            val intent = Intent(requireActivity(), AttestationActivity::class.java)
            val curriculumItems = viewModel.curriculumData.value?.get(Calendar.getInstance().timeInMillis.toDateYyyyMMdd())
            if (curriculumItems.isNullOrEmpty()) {
                return@setOnClickListener ToastUtil.showToast(this@ClassCurriculumFragment.requireContext(), "未获取到今日的课表数据")
            }
            intent.putExtra(EXTRA_DATA, ArrayList(curriculumItems))
            startActivityForResult(intent, AttestationActivity.CURRICULUM)
        }
        binding.titleRecycler.adapter = titleAdapter
        binding.recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                binding.titleRecycler.scrollBy(dx, dy)
            }
        })
        binding.titleRecycler.addItemDecoration(GridSpacingItemDecoration(1, dp2px(8.dp).toInt(), false))
        binding.recycler.addItemDecoration(GridSpacingItemDecoration(7, dp2px(8.dp).toInt(), false))

        viewModel.weekData.observe(viewLifecycleOwner) {
            headerAdapter.notifyChanged(it)
        }
        viewModel.titleData.observe(viewLifecycleOwner) {
            titleAdapter.notifyChanged(it)
        }
        viewModel.data.observe(viewLifecycleOwner) {
            adapter.notifyChanged(it)
            if (lastSuccessTime == 0L && it.isNotEmpty()) lastSuccessTime = System.currentTimeMillis()
        }
        viewModel.curriculumData.observe(viewLifecycleOwner) {

        }
    }

    override fun onResume() {
        super.onResume()
        if (System.currentTimeMillis() - lastSuccessTime > 1 * 60 * 60 * 1000) {
            viewModel.load()
            lastSuccessTime = 0L
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        onResult(requestCode, resultCode, data)
    }
}
